package com.caijb.redisdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * @author caijb
 * @version 1.0
 * @data 2025/11/1 18:14
 */

@Component
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // 设置 key 的序列化方式
        template.setKeySerializer(new StringRedisSerializer());

        // 设置 hash key 的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());

        // 设置 value 的序列化方式
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        // 设置 hash value 的序列化方式
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.afterPropertiesSet();
        return template;
    }
}
